package com.tim.app.ui.activity.setting;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.SmoothSwitchScreenUtil;
import com.application.library.util.StringUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.callback.LoginCallBack;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.WindowUtils;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.SignRequestParams;
import com.tim.app.server.result.GetValidationCodeResult;
import com.tim.app.server.result.LoginResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.ThirdAuthResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.dialog.TipDialog;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.UMLoginUtil;
import com.tim.app.util.ViewGT;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 注册页面
 * create at 2016/7/13
 */
public class RegisterActivity extends BaseActivity {

    private static final String TAG = "RegisterActivity";

    private EditText input_phone_num, input_sms_mark, input_password;
    private TextView show_time;
    private CountDownTimer timer;
    private boolean isTiming = false;
    private String phone, password, smscode;
    private Button btRegist;
    private TextView tvSocailAccountsLogin;
    private LinearLayout llSocialAccounts;
    private UMLoginUtil loginUtil;

    private ImageView ivPassword;

    private TextView tvAgreement;

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        SmoothSwitchScreenUtil.smoothSwitchScreen(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        input_phone_num = (EditText) findViewById(R.id.et_input_phone_num);
        input_sms_mark = (EditText) findViewById(R.id.register_input_sms_mark);
        show_time = (TextView) findViewById(R.id.register_get_sms_mark_tx);
        input_password = (EditText) findViewById(R.id.et_input_password);
        input_phone_num.addTextChangedListener(new MyEditChangeListener());
        input_sms_mark.addTextChangedListener(new MyEditChangeListener());
        input_password.addTextChangedListener(new MyEditChangeListener());
        ivPassword = (ImageView) findViewById(R.id.ivPassword);
        btRegist = (Button) findViewById(R.id.btRegist);
        tvAgreement = (TextView) findViewById(R.id.tvAgreement);
        tvSocailAccountsLogin = (TextView) findViewById(R.id.tvSocailAccountsLogin);
        llSocialAccounts = (LinearLayout) findViewById(R.id.llSocialAccounts);
        findViewById(R.id.iv_back).setOnClickListener(this);
        tvSocailAccountsLogin.setOnClickListener(this);
        findViewById(R.id.register_get_sms_mark_tx).setOnClickListener(this);
        findViewById(R.id.tvGotoLogin).setOnClickListener(this);
        btRegist.setOnClickListener(this);
        llSocialAccounts.setVisibility(View.GONE);
        findViewById(R.id.llLoginQQ).setOnClickListener(this);
        findViewById(R.id.llLoginWx).setOnClickListener(this);
        findViewById(R.id.llLoginSina).setOnClickListener(this);
        ivPassword.setOnClickListener(this);
        tvAgreement.setOnClickListener(this);

        timer = new CountDownTimer(AppKey.VERTIFY_SECONDS * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                show_time.setText(millisUntilFinished / 1000 + getString(R.string.txt_bind_resend));
            }

            @Override
            public void onFinish() {
                isTiming = false;
                show_time.setText(getString(R.string.get_sms_mark));
                findViewById(R.id.register_get_sms_mark_tx).setEnabled(true);
            }
        };
        loginUtil = new UMLoginUtil(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (AppKey.TYPE_MOBILE_REGIST == requestCode) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    private class MyEditChangeListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            updateBtn();
        }
    }

    private void updateBtn() {
        if (TextUtils.isEmpty(input_phone_num.getText().toString().trim()) ||
                TextUtils.isEmpty(input_password.getText().toString().trim()) || TextUtils.isEmpty(input_sms_mark.getText().toString().trim())) {
            btRegist.setEnabled(false);
        } else {
            btRegist.setEnabled(true);
        }
    }

    @Override
    public void initData() {
    }

    private void appLogin(final int platformType, final String platformUid, final String accessToken) {
        showLoadingDialog(R.string.loading_login);
        API_User.ins().loginByThird(TAG, platformType, platformUid, accessToken, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                String type = "";
                if (platformType == AppKey.LOGIN_TYPE_SINA) {
                    type = "wb";
                } else if (platformType == AppKey.LOGIN_TYPE_QQ) {
                    type = "qq";
                } else if (platformType == AppKey.LOGIN_TYPE_WX) {
                    type = "wx";
                }
                if (errCode == ResponseResult.ResultStatus.OK && !TextUtils.isEmpty(resultValue)) {
                    LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        if (result.getRes().getHashmap().getIsPerfectInfo() == 1) {
                            PerfectPersonInfomationActivity.start(RegisterActivity.this, result.getRes().getHashmap().getUser(), AppKey.LOGIN_TYPE_MOBILE, -1);
                        } else {
                            if (null != result.getRes().getHashmap().getUser()) {
                                UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                            }
                            if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                            }
                            UserManager.ins().saveLoginType(type);
                            API_Statistics.ins().addLoginData(TAG, RegisterActivity.this, type, platformUid);

                            Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                            startActivity(intent);
                            setResult(RESULT_OK);
                            RegisterActivity.this.finish();
                            WindowUtils.getInStance().clearList();
                        }
                    }
                } else if (errCode == ResponseResult.ResultStatus.UN_REGIST) {
                    ThirdAuthResult result = new Gson().fromJson(resultValue, ThirdAuthResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getPlatformuserobj()) {
                        User user = new User();
                        user.setImage(result.getRes().getPlatformuserobj().getProfileImageUrl());
                        user.setName(result.getRes().getPlatformuserobj().getScreenName());
                        user.setSex(result.getRes().getPlatformuserobj().getGender());
                        BindMobileOrResetPasswordActivity.startBindMobileOrResetPasswordActivity(RegisterActivity.this, user, platformType, AppKey.TYPE_BING_MOBILE, platformUid, accessToken, AppKey.CODE_LOGIN_BIND_MOBILE);
                    }
                } else if (errCode == ResponseResult.ResultStatus.SUSPENED) {
                    ToastUtil.showToast(getString(R.string.suspenedPrompt));
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btRegist) {
            phone = input_phone_num.getText().toString();
            password = input_password.getText().toString();
            smscode = input_sms_mark.getText().toString();
            if (checkRegisterEnable()) {
                bingRegist(smscode, password);
            }
        } else if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.tvGotoLogin) {
            boolean login = getIntent().getBooleanExtra("login", false);
            if (login) {
                startActivity(new Intent(RegisterActivity.this, PhoneLoginActivity.class));
            }
            finish();
        } else if (v.getId() == R.id.register_get_sms_mark_tx) {
            if (isTiming) {
                return;
            }
            phone = input_phone_num.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.showToast(RT.getString(R.string.input_phone_num));
                return;
            }
            if (!phone.matches(StringUtil.ZHENGZE_PHONE)) {
                ToastUtil.showToast(RT.getString(R.string.error_mobile_error));
                return;
            }
            getVerifyApi();
        } else if (v.getId() == R.id.tvSocailAccountsLogin) {
            llSocialAccounts.setVisibility(View.VISIBLE);
        } else if (v.getId() == R.id.llLoginQQ) {
            loginUtil.login(SHARE_MEDIA.QQ, new LoginCallBack() {
                @Override
                public void onFailed(String msg) {
                    ToastUtil.showToast(RT.getString(R.string.error_login_qq));
                }

                @Override
                public void onSuccess(String unionId, String name, String avatar, String token) {
                    appLogin(AppKey.LOGIN_TYPE_QQ, unionId, token);
                }
            });
        } else if (v.getId() == R.id.llLoginWx) {
            loginUtil.login(SHARE_MEDIA.WEIXIN, new LoginCallBack() {
                @Override
                public void onFailed(String msg) {
                    ToastUtil.showToast(RT.getString(R.string.error_login_wx));
                }

                @Override
                public void onSuccess(String unionid, String name, String avatar, String token) {
                    appLogin(AppKey.LOGIN_TYPE_WX, unionid, token);
                }
            });
        } else if (v.getId() == R.id.llLoginSina) {
            loginUtil.login(SHARE_MEDIA.SINA, new LoginCallBack() {
                @Override
                public void onFailed(String msg) {
                    ToastUtil.showToast(RT.getString(R.string.error_login_sina));
                }

                @Override
                public void onSuccess(String unionId, String name, String avatar, String token) {
                    appLogin(AppKey.LOGIN_TYPE_SINA, unionId, token);
                }
            });
        } else if (v.getId() == R.id.ivPassword) {
            if (ivPassword.isSelected()) {
                ivPassword.setSelected(false);
                input_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                ivPassword.setSelected(true);
                input_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            input_password.postInvalidate();
            //切换后将EditText光标置于末尾
            CharSequence charSequence = input_password.getText();
            if (charSequence instanceof Spannable) {
                Spannable spanText = (Spannable) charSequence;
                Selection.setSelection(spanText, charSequence.length());
            }
        } else if (v.getId() == R.id.tvAgreement) {
            ViewGT.gotoGeneralWebActivity(this, "https://www.urmoli.com/app/protocol", false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (input_phone_num != null) {
            SoftKeyboardUtil.hideSoftKeyboard(input_phone_num);
        }
        if (input_sms_mark != null) {
            SoftKeyboardUtil.hideSoftKeyboard(input_sms_mark);
        }
        if (input_password != null) {
            SoftKeyboardUtil.hideSoftKeyboard(input_password);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null && isTiming) {
            timer.cancel();
        }
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    private boolean checkRegisterEnable() {
        return checkRegister(phone, password, smscode);
    }

    /**
     * 检测注册参数
     *
     * @param phone
     * @param password
     * @param smscode
     * @return
     */
    public boolean checkRegister(String phone, String password, String smscode) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_empty));
            return false;
        }
        if (!phone.matches(StringUtil.ZHENGZE_PHONE)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_error));
            return false;
        }
        if (TextUtils.isEmpty(smscode)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_vertify));
            return false;
        }
        if (TextUtils.isEmpty(password) || !password.matches(StringUtil.ZHENGZE_PASSWORD)) {
            ToastUtil.showToast(RT.getString(R.string.error_password));
            return false;
        }
        return true;
    }

    /**
     * 获取验证码
     */
    private void getVerifyApi() {
        showLoadingDialog();
        API_User.ins().getPhoneVerificationCode(TAG, AppKey.VERTIFY_REGISTER, phone, -1, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean fromCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    ToastUtil.showToast("短信验证码已发送");
                    show_time.setEnabled(false);
                    isTiming = true;
                    timer.start();
                    if (!TextUtils.isEmpty(resultValue)) {
                        GetValidationCodeResult result = new Gson().fromJson(resultValue, GetValidationCodeResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                            if (!TextUtils.isEmpty(result.getRes().getHashmap().getPhoneauth())) {
                                input_sms_mark.setText(result.getRes().getHashmap().getPhoneauth());
                            }
                        }
                    }
                } else if (errCode == ResponseResult.ResultStatus.HAS_BIND) {
                    final TipDialog tipDialog = new TipDialog(RegisterActivity.this);
                    tipDialog.setTextDes("该手机号已经注册，是否直接登录？");
                    tipDialog.setButton1("取消", new TipDialog.DialogButtonOnClickListener() {
                        @Override
                        public void onClick(View button, TipDialog dialog) {
                            tipDialog.dismiss();
                        }
                    });
                    tipDialog.setButton2("登录", new TipDialog.DialogButtonOnClickListener() {
                        @Override
                        public void onClick(View button, TipDialog dialog) {
                            tipDialog.dismiss();
                            ViewGT.gotoLoginActivity(RegisterActivity.this);
                        }
                    });
                    tipDialog.show();
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 注册
     *
     * @param validationCode
     */
    private void bingRegist(String validationCode, String password) {
        showLoadingDialog();
        API_User.ins().regist(TAG, AppKey.LOGIN_TYPE_MOBILE, phone, SignRequestParams.MDString(password), validationCode, "", "", new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                String type = "";
                if (errCode == ResponseResult.ResultStatus.OK) {
                    if (!TextUtils.isEmpty(resultValue)) {
                        LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                            if (result.getRes().getHashmap().getIsPerfectInfo() == 1) {
                                PerfectPersonInfomationActivity.start(RegisterActivity.this, result.getRes().getHashmap().getUser(), AppKey.LOGIN_TYPE_MOBILE, -1);
                            } else {
                                if (null != result.getRes().getHashmap().getUser()) {
                                    UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                                }
                                if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                    UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                                }
                                UserManager.ins().saveLoginType(type);
                                EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                                API_Statistics.ins().addRegistData(TAG, RegisterActivity.this, type);
                                UserManager.ins().loginChat(result.getRes().getHashmap().getUser().getUserId());
                                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                                startActivity(intent);
                                setResult(RESULT_OK);
                                finish();
                            }
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

}
